<style lang="less">
@import url(../../../node_modules/@wangeditor/editor/dist/css/style.css);

.edit-article {
  padding-top: 15px;

  .edit-article-header {
    .opt {
      margin-bottom: 15px;
    }

    .my-select {
      margin-left: 15px;
    }

    .preview-img {
      width: 360px;
      height: 180px;
      border-radius: 4px;
    }

    .el-upload-list {
      display: none;
    }
  }
}
</style>
<template>
  <div class="edit-article">
    <header class="edit-article-header">
      <el-form :model="article" label-width="100px">
        <el-form-item label="文章标题">
          <el-input v-model="article.title" placeholder="请输入文章标题" :disabled="isNormalUser"></el-input>
        </el-form-item>

        <el-form-item label="作者">
          <el-input v-model="article.author" placeholder="请输入作者" :disabled="isNormalUser"></el-input>
        </el-form-item>

        <el-form-item label="分类">
          <el-select @change="changeCateFn" v-model="article.cate" placeholder="请选择一级分类" :disabled="isNormalUser">
            <el-option v-for="item in options" :key="item.value" :label="item.label" :value="item.value">
            </el-option>
          </el-select>

          <el-select v-if="category_options.length != 0" class="my-select" v-model="article.category"
            placeholder="请选择二级分类" :disabled="isNormalUser">
            <el-option v-for="item in category_options" :key="item.value" :label="item.label" :value="item.value">
            </el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="文章状态" v-if="!isNormalUser">
          <el-select v-model="article.status" placeholder="请选择文章状态">
            <el-option label="草稿" value="draft"></el-option>
            <el-option label="已发布" value="published"></el-option>
            <el-option label="已下架" value="offline"></el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="是否置顶" v-if="isAdmin">
          <el-switch v-model="article.is_top" :active-value="1" :inactive-value="0"></el-switch>
        </el-form-item>

        <el-form-item label="文章内容">
          <div style="border: 1px solid #dcdfe6; border-radius: 4px;">
            <Toolbar v-if="!isNormalUser && editorReady" style="border-bottom: 1px solid #dcdfe6" :editor="editor"
              :defaultConfig="toolbarConfig" :mode="mode" />
            <Editor v-if="editorReady" style="height: 500px; overflow-y: hidden;" 
              v-model="html"
              :defaultHtml="isNormalUser ? articleContent : undefined"
              :defaultConfig="editorConfig" :mode="mode"
              @onCreated="onCreated" :read-only="isNormalUser" />
            <div v-else style="height: 500px; padding: 20px; overflow-y: auto; color: #999; display: flex; align-items: center; justify-content: center;">
              加载中...
            </div>
          </div>
        </el-form-item>

        <el-form-item label="封面图片">
          <div style="display: flex;">
            <el-upload v-if="!isNormalUser" class="upload-demo" drag action="" :on-change="changeFn"
              :auto-upload="false" accept="image/*">
              <i class="el-icon-upload"></i>
              <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
              <div class="el-upload__tip" slot="tip">只能上传jpg/png文件，且不超过500kb</div>
            </el-upload>

            <div v-if="src" style="text-align: center; margin-left: 15px">
              <img class="preview-img" :src="src" alt="封面预览">
            </div>
          </div>
        </el-form-item>

        <el-form-item label="标签">
          <el-input v-model="article.tag" placeholder="请输入标签，多个标签用逗号分隔" :disabled="isNormalUser"></el-input>
        </el-form-item>

        <el-form-item>
          <el-button v-if="!isNormalUser" type="primary" @click="submitFn">保存修改</el-button>
          <el-button @click="goBack">返回</el-button>
        </el-form-item>
      </el-form>
    </header>
  </div>
</template>

<script>
import { Editor, Toolbar } from '@wangeditor/editor-for-vue'
import { listCate, uploadPhoto, isLogined, getArticleDetail, modifyArticle, host, getCurrentUserDetail } from "../../api/index"

export default {
  components: { Editor, Toolbar },
  data() {
    return {
      articleId: null,
      article: {
        title: "",
        author: "",
        cate: "",
        category: "",
        tag: "",
        status: "published",
        is_top: 0
      },
      options: [], // 一级分类选项（动态加载）
      category_options: [],
      editor: null,
      html: '',
      toolbarConfig: {},
      editorConfig: {
        placeholder: '请输入内容...',
        readOnly: false, // 将在组件中动态设置
        // 在只读模式下禁用所有交互
        autoFocus: false,
        MENU_CONF: {
          uploadImage: {
            server: `${host}/api/photo/upload_img`,
            fieldName: 'photo',
          }
        }
      },
      mode: 'default',
      src: "",
      cateArr: [],
      file: null,
      originalSrc: "",
      isNormalUser: false, // 是否为普通用户（非管理员且非作者）
      articleUserId: null, // 文章的作者id
      currentUserId: null, // 当前登录用户的id
      originalIsTop: 0, // 保存文章原始的置顶状态
      editorReady: false, // 编辑器是否准备好渲染
      articleContent: '' // 文章内容（用于延迟设置）
    }
  },
  computed: {
    // 判断是否为普通用户（role !== '1' 表示普通用户）
    userRole() {
      return localStorage.getItem("USER_ROLE") || '0'
    },
    // 判断是否为管理员
    isAdmin() {
      const role = localStorage.getItem("USER_ROLE") || '0'
      return role === '1'
    }
  },
  methods: {
    // 上传封面图片
    async uploadPhotoFn() {
      if (this.file) {
        let formData = new FormData()
        formData.append("photo", this.file)
        return await uploadPhoto(formData)
      }
      return null
    },
    // 选择一级分类
    changeCateFn(value) {
      this.article.cate = value
      let arr = this.cateArr.filter(item => {
        return item.cate == value
      })
      let newArr = arr.map(item => {
        return {
          value: item.cate_name,
          label: item.cate_name,
        }
      })
      this.category_options = newArr
      if (newArr.length > 0 && !this.article.category) {
        this.article.category = arr[0].cate_name
      }
    },
    // 获取导航分类列表
    async listCateFn() {
      await listCate().then(resData => {
        if (resData.code == 200) {
          let { result } = resData
          this.cateArr = result
          // 动态生成一级分类选项
          const parentCates = new Set()
          result.forEach(item => {
            if (item.cate) {
              parentCates.add(item.cate)
            }
          })
          this.options = Array.from(parentCates).map(cate => ({
            value: cate,
            label: cate
          }))
        }
      })
    },
    // 获取文章详情
    async getArticleDetailFn() {
      const id = this.$route.query.id
      if (!id) {
        this.$message.error('缺少文章ID')
        this.goBack()
        return
      }
      this.articleId = id
      await getArticleDetail({ id })
        .then(resData => {
          if (resData.code == 200 && resData.result && resData.result.length > 0) {
            const articleData = resData.result[0]
            this.article.title = articleData.title || ""
            this.article.author = articleData.author || ""
            this.article.cate = articleData.cate || ""
            this.article.category = articleData.cate_name || ""
            this.article.tag = articleData.tag || ""
            this.article.status = articleData.status || "published"
            this.article.is_top = articleData.is_top || 0
            // 保存文章原始的置顶状态
            this.originalIsTop = articleData.is_top || 0
            // 保存文章作者id
            this.articleUserId = articleData.user_id || null

            // 先设置其他数据
            this.originalSrc = articleData.src || ""
            this.src = articleData.src ? host + articleData.src : ""

            // 保存文章内容
            this.articleContent = articleData.content || ""

            // 判断是否可以编辑：管理员或文章作者可以编辑，否则只读
            this.checkEditPermission()

            // 设置分类选项
            if (this.article.cate) {
              this.changeCateFn(this.article.cate)
            }

            // 在只读模式下，延迟更长时间确保配置完全准备好
            // 非只读模式可以立即渲染
            const delay = this.isNormalUser ? 500 : 100
            setTimeout(() => {
              this.editorReady = true
              // 编辑器渲染后，设置内容
              this.$nextTick(() => {
                this.setEditorContent()
              })
            }, delay)
          } else {
            this.$message.error('获取文章详情失败')
            this.goBack()
          }
        })
        .catch(err => {
          console.error('获取文章详情失败:', err)
          this.$message.error('获取文章详情失败')
          this.goBack()
        })
    },
    // 安全地设置编辑器内容
    setEditorContent() {
      if (!this.editor || !this.articleContent) {
        return
      }

      const setContent = () => {
        try {
          const content = this.articleContent
          
          // 检查编辑器是否已经完全初始化（DOM 是否准备好）
          const isEditorReady = () => {
            try {
              // 尝试获取编辑器的 DOM 元素
              if (this.editor.getEditableContainer) {
                const container = this.editor.getEditableContainer()
                return container && container.querySelector
              }
              return true // 如果方法不存在，假设已准备好
            } catch {
              return false
            }
          }
          
          if (isEditorReady()) {
            // DOM 已准备好，可以安全设置内容
            try {
              // 在只读模式下，优先使用 setHtml 方法
              if (this.isNormalUser && this.editor.setHtml) {
                this.editor.setHtml(content)
              } else {
                // 非只读模式或 setHtml 不可用，直接设置 html
                this.html = content
              }
            } catch (err) {
              console.error('设置编辑器内容失败:', err)
              // 如果失败，尝试直接设置 html
              this.html = content
            }
          } else {
            // DOM 还没准备好，延迟设置
            setTimeout(() => {
              if (isEditorReady()) {
                try {
                  if (this.isNormalUser && this.editor.setHtml) {
                    this.editor.setHtml(content)
                  } else {
                    this.html = content
                  }
                } catch (err) {
                  this.html = content
                }
              } else {
                // 如果还是没准备好，直接设置 html（让编辑器自己处理）
                this.html = content
              }
            }, 200)
          }
        } catch (error) {
          console.error('设置编辑器内容失败:', error)
          // 如果设置失败，尝试直接设置 html
          this.html = this.articleContent
        }
      }

      // 如果编辑器还没创建，等待创建后再设置
      if (this.editor) {
        this.$nextTick(() => {
          setContent()
        })
      } else {
        setTimeout(() => {
          if (this.editor) {
            setContent()
          } else {
            // 如果编辑器还没创建，再等待
            setTimeout(() => {
              if (this.editor) {
                setContent()
              }
            }, 200)
          }
        }, 100)
      }
    },
    // 检查编辑权限
    checkEditPermission() {
      const role = localStorage.getItem("USER_ROLE") || '0'
      const isAdmin = role === '1'
      const isAuthor = this.currentUserId && this.articleUserId &&
        String(this.currentUserId) === String(this.articleUserId)
      // 如果URL中有readonly参数，或者既不是管理员也不是作者，则只读
      const hasReadonlyParam = this.$route.query.readonly === 'true'
      this.isNormalUser = hasReadonlyParam || (!isAdmin && !isAuthor)

      // 设置编辑器为只读模式
      if (this.isNormalUser) {
        this.editorConfig.readOnly = true
        // 如果编辑器已经创建，延迟设置只读模式
        if (this.editor) {
          this.$nextTick(() => {
            try {
              // 使用更安全的方式设置只读
              if (this.editor.getConfig) {
                const config = this.editor.getConfig()
                if (config) {
                  config.readOnly = true
                }
              }
              // 如果 disable 方法存在，也调用它
              if (this.editor.disable) {
                this.editor.disable()
              }
            } catch (error) {
              console.error('设置编辑器只读模式失败:', error)
            }
          })
        }
      } else {
        this.editorConfig.readOnly = false
        // 如果编辑器已经创建，确保启用编辑
        if (this.editor) {
          this.$nextTick(() => {
            try {
              if (this.editor.getConfig) {
                const config = this.editor.getConfig()
                if (config) {
                  config.readOnly = false
                }
              }
              if (this.editor.enable) {
                this.editor.enable()
              }
            } catch (error) {
              console.error('启用编辑器失败:', error)
            }
          })
        }
      }
    },
    // 加载当前用户id
    async loadCurrentUserId() {
      const token = localStorage.getItem("AUTO_TOKEN")
      if (token) {
        try {
          const resData = await getCurrentUserDetail()
          if (resData && resData.code === 200 && resData.data) {
            this.currentUserId = resData.data.id
            // 加载用户信息后，再次检查编辑权限
            this.checkEditPermission()
          }
        } catch (error) {
          console.error('获取用户信息失败:', error)
        }
      }
    },
    // 富文本编辑器创建完成
    onCreated(editor) {
      this.editor = Object.seal(editor)
      // 如果已经是只读模式，确保编辑器处于只读状态
      if (this.isNormalUser && editor) {
        this.$nextTick(() => {
          try {
            // 确保编辑器配置为只读
            if (editor.getConfig) {
              const config = editor.getConfig()
              if (config) {
                config.readOnly = true
              }
            }
            // 如果编辑器有 disable 方法且当前不是只读，则禁用
            if (editor.disable && !this.editorConfig.readOnly) {
              editor.disable()
            }
          } catch (error) {
            console.error('设置编辑器只读模式失败:', error)
          }
        })
      }
      
      // 如果内容已经准备好，设置编辑器内容
      if (this.articleContent) {
        // 延迟设置，确保编辑器 DOM 完全准备好
        setTimeout(() => {
          this.setEditorContent()
        }, this.isNormalUser ? 300 : 100)
      }
    },
    // 选择封面图片
    changeFn(info) {
      let file = info.raw
      const reader = new FileReader()
      reader.onload = () => {
        this.src = reader.result
      }
      if (file) {
        reader.readAsDataURL(file)
        this.file = file
      }
      return false
    },
    // 提交修改
    async submitFn() {
      // 普通用户不能修改
      if (this.isNormalUser) {
        this.$message({ type: "warning", message: "普通用户无法修改文章" })
        return
      }

      let html = this.html
      let { title, author, cate, category, tag, status, is_top } = this.article

      if (!title || !author || !cate || !category || !tag || !html) {
        this.$message({ type: "error", message: "请填写完整信息" })
        return
      }

      let src = this.originalSrc
      // 如果上传了新图片，先上传图片
      if (this.file) {
        let result = await this.uploadPhotoFn()
        if (result && result.picUrl) {
          src = result.picUrl
        } else {
          this.$message({ type: "error", message: "图片上传失败，请重试" })
          return
        }
      }

      let token = localStorage.getItem("AUTO_TOKEN")
      if (!token) {
        this.$message({ type: "error", message: "您还没有登录" })
        return
      }

      // 如果是管理员，可以使用表单中的 is_top 值；否则保持原有的置顶状态
      const role = localStorage.getItem("USER_ROLE") || '0'
      const isAdmin = role === '1'
      const topValue = isAdmin
        ? (is_top !== undefined && is_top !== null ? is_top : 0)
        : this.originalIsTop

      await modifyArticle({
        token,
        id: this.articleId,
        title,
        author,
        cate,
        cate_name: category,
        content: html,
        src,
        tag,
        status: status || 'published',
        is_top: topValue
      })
        .then(resData => {
          if (resData.code == 200) {
            this.$message({ type: "success", message: resData.msg || "修改成功" })
            this.goBack()
          } else {
            this.$message({ type: "error", message: resData.msg || "修改失败" })
          }
        })
        .catch(err => {
          console.error('修改文章失败:', err)
          this.$message({ type: "error", message: "修改失败，请重试" })
        })
    },
    // 返回
    goBack() {
      this.$router.push({ path: "/article_list" })
    }
  },
  beforeDestroy() {
    const editor = this.editor
    if (editor == null) return
    editor.destroy()
  },
  async created() {
    this.$store.commit("addTab", this.$route)
    // 先加载当前用户id
    await this.loadCurrentUserId()
    // 检查URL参数，提前设置只读状态
    if (this.$route.query.readonly === 'true') {
      this.isNormalUser = true
      this.editorConfig.readOnly = true
    }
    // 先加载分类数据，再加载文章详情
    await this.listCateFn()
    this.getArticleDetailFn()
  },
  watch: {
    $route: {
      immediate: true,
      deep: true,
      handler(newRoute) {
        this.$store.commit("addTab", newRoute)
      }
    }
  },
  async beforeRouteEnter(to, from, next) {
    let token = localStorage.getItem("AUTO_TOKEN")
    if (token) {
      try {
        const resData = await isLogined({ token })
        if (resData && resData.msg == '用户登录在线状态') {
          next()
        } else {
          // 未登录，重定向到登录页
          next({ path: "/login" })
        }
      } catch (err) {
        // 登录检查失败，重定向到登录页
        next({ path: "/login" })
      }
    } else {
      // 没有token，重定向到登录页
      next({ path: "/login" })
    }
  },
}
</script>
